// 登录页面
import React from 'react'
import Layout from './Layout'
import { Form, Input, Button } from 'antd';
import { API } from '../../config'
import axios from 'axios'
import { useHistory } from "react-router-dom"


function Login() {
	const history = useHistory()
	// 获取表单实例对象
	const [form] = Form.useForm() 
	// 提交
	const onFinish = async value => {
		console.log(value);
		// 登录请求
		let { data } = await axios.post(`${API}/signin`,value)
		console.log(data);
		// 将用户信息存储到localStorage
		localStorage.setItem('user', JSON.stringify(data))
		// 根据当前的用户角色,来指定不同的路由
		const url = data.user.role === 1 ? '/admin/dashboard' : '/user/dashboard'
		// 登录成功后自动跳转到指定页面
		history.push(url)
	}
	return (
		<>
			<Layout title="登录">
				<Form
					form={form}
      	  onFinish={onFinish}
    		>
      	  <Form.Item
      	    label="邮箱"
      	    name="email"
      	    rules={[{ required: true, message: '请输入你的邮箱!' }]}
      	  >
      	    <Input />
      	  </Form.Item> 
      	  <Form.Item
      	    label="密码"
      	    name="password"
      	    rules={[{ required: true, message: '请正确输入你的密码!', min:6, max:18 }]}
      	  >
      	    <Input.Password />
      	  </Form.Item>
					<Form.Item>
      	  	<Button type="primary" htmlType="submit">
      	  	  登录
      	  	</Button>
      		</Form.Item>
				</Form>
			</Layout>
		</>
	)
}

export default Login
